import React, { useEffect, useRef, useState } from "react";
import { Modal,Divider,Alert} from 'antd';
import classNames from "classnames";
import axios from 'axios'
  // 将时间转化为秒
  const ToSeconds = (t) => {
    var s = 0.0
    if (t) {
      var p = t.split(':')
      for (let i = 0; i < p.length; i++) {
        s = s * 60 + parseFloat(p[i].replace(',', '.'))
      }
    }
    return s * 1000
  }
 const getText = (textItem) => {
    let value = ''
    textItem.forEach((i, index) => {
      if (index > 1 && index < textItem.length) {
        value = value + i
      }
    })
    return value
  }
      // 获取字幕内容，发送一个get请求
    const  GetSrtInfo = (srtUrl,setSrtData) => {
        var reg = /[-�〝\]\[\)\(\{\}［］＂〞´ˋ〈〉「」『』︵︷︿︹︽﹁﹃︻ˆ？！﹍﹎_＿﹏﹌￣ˉ﹊﹉¡¿ˇ︼﹄﹂︾︺﹀︸︶]/g
        axios
          .get(`${srtUrl}`)
          .then(function(response) {
              console.log(response);

              response.data=response.text

            let a = null
            if (response.data.indexOf('\n\r\n') !== -1) {
              a = response.data.split(/\n\r\n/)
            } else {
              a = response.data.split(/\n\n/)
            }
            for (let i = 0; i < a.length; i++) {
              if (a[i].indexOf('\n') === 0) {
                a[i] = a[i].slice(1)
                if (a[i].indexOf('\n') === 0) {
                  a[i] = a[i].slice(1)
                }
              }
            }
            const textList = a
              .filter(item => item !== '')
              .map((item, index) => {
                const textItem = item.split(/\n/)
                return {
                  show: false,
                  showBefore: false,
                  index: index,
                  sort: textItem[0],
                  value: getText(textItem).replace(reg, ''),
                  bg: ToSeconds(textItem[1].split(' --> ')[0]),
                  ed: ToSeconds(textItem[1].split(' --> ')[1]),
                  timeLine: textItem[1]
                }
              })
              setSrtData(textList)
          })
      }
    

const PreviewAudio = (props) => {
  const {isModalVisible, setIsModalVisible,prevewAudio} = props

  const [time,setTime] = useState(0)
  const [srtData,setSrtData] = useState([])

  const audio = useRef(null)

  useEffect(()=>{
    if(!isModalVisible) return
     if(prevewAudio.audioUrl&&prevewAudio.srtUrl){
        GetSrtInfo(prevewAudio.srtUrl,setSrtData)

        setTimeout(()=>{
            if(audio.current){
                audio.current.load()
    
                audio.current.oncanplay=()=>{
                    audio.current.play()
                }
            }
        },500)
     }

     return ()=>{
        setTime(0)
        setSrtData([])
     }
  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps



  // 返回
  const handleOk = async () => {
    setIsModalVisible(false);
  }
  const onCancel = () => {
    setIsModalVisible(false);
  };
  // 播放中
  const onTimeUpdate = (e) => {
    setTime(e.target.currentTime*1000)
  }
  
  return   <Modal destroyOnClose wrapClassName="modal-full"   visible={isModalVisible} onOk={handleOk} onCancel={onCancel}>
      <div className="full-modal-title">
          <Alert message={'音频预览'} type="success" />
      </div>

      <audio ref={audio} src={prevewAudio.audioUrl} controls style={{width:'100%'}}  onTimeUpdate={onTimeUpdate}></audio>

      <Divider>字幕预览</Divider>

      <div className="srt-show">
        {
          srtData?<ul>
          {
            srtData.map((i,j)=>{
              return <li key={j} className={classNames(i.bg<time&&i.ed>time?'text-srt-active':'')}>
                {i.value}
              </li>
            })
          }
        </ul>:'无字幕'
        }
      </div>
   </Modal>

}
export default PreviewAudio